<?php
include COMMON_PATH . 'Common/static_file.php';
/*
 * 公共日志函数
 * $message 内容
 * $level (EMERG ALERT CRIT ERR WARN NOTICE INFO DEBUG SQL)
 * $file_name 文件名 不需写日期
 */
function sys_log($message, $level, $file_name) {
	$destination = LOG_PATH . 'SYS/' . $file_name . date('y_m_d') . '.log';
	Think\Log::write($message, $level, '', $destination);
}

function sql_log($sql, $result = null, $file_name = 'sql_log.') {
	if (empty($result)) {
		$result = "";
	} else {
		$result = '[' . $result . ']';
	}

	$message = $sql . $result . chr(10);
	sys_log($message, "SQL", $file_name);
}

function sql_operate_log($sql, $result) {
	sql_log($sql, $result, 'sql_operation_log.');
}

// 日志例子
function sys_debug_log($message) {
	sys_log($message, "DEBUG", "sys_debug_log");
}

// 日志例子
function sys_pay_log($message) {
	sys_log($message, "DEBUG", "sys_pay_log");
}

// $method => POST GET
function sys_http_log($method, $message) {
	sys_log($message, $method, "sys_http_log");
}

//短信的日志
function sys_sms_log($message) {
	sys_log($message, "INFO", "sys_sms_log");
}

function app_log($file_name, $message) {

	sys_log($message, "INFO", $file_name);
}

function num_f($a) {
	return round($a, C('PRECISION'));
}

function cmp_f($a, $op, $b) {
	$str = "\$ret_val = num_f(\$a - \$b" . ") " . $op . "0;";
	eval($str);
	return $ret_val;
}

/**
+----------------------------------------------------------
 *  分类树
+----------------------------------------------------------
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0) {
	// 创建Tree
	$tree = array();
	if (is_array($list)) {
		// 创建基于主键的数组引用
		$refer = array();
		foreach ($list as $key => $data) {
			$refer[$data[$pk]] = &$list[$key];
		}
		foreach ($list as $key => $data) {
			// 判断是否存在parent
			$parentId = $data[$pid];
			if ($root == $parentId) {
				$tree[] = &$list[$key];
			} else {
				if (isset($refer[$parentId])) {
					$parent           = &$refer[$parentId];
					$parent[$child][] = &$list[$key];
				}
			}
		}
	}
	return $tree;
}

/**
 * 远程获取数据，POST模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * @param $url 指定URL完整路径地址
 * @param $para 请求的数据
 * @param $input_charset 编码格式。默认值：空值
 * return 远程输出的数据
 */
function httpResponsePOST($url, $para ,$header=null) {
	$curl = curl_init($url);
	if(is_array($para)){
		$para = yzg_array_filter($para);
	}
	$header[] = 'Expect:';
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //SSL证书认证
	curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果
	curl_setopt($curl, CURLOPT_POST, true); // post传输数据
	curl_setopt($curl, CURLOPT_POSTFIELDS, $para); // post传输数据
	curl_setopt($curl, CURLOPT_TIMEOUT, 5); //过期时间秒
	curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //http://www.laruence.com/2011/01/20/1840.html
	$responseText = curl_exec($curl);
	curl_close($curl);
	return $responseText;
}

/**
 * 远程获取数据，GET模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * @param $url 指定URL完整路径地址
 * return 远程输出的数据
 */
function httpResponseGET($url) {
	$curl = curl_init($url);
	$this_header = array(
	"content-type: application/x-www-form-urlencoded;charset=UTF-8"
	);
	curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //SSL证书认证
	curl_setopt($curl, CURLOPT_HTTPHEADER, $this_header);
	$responseText = curl_exec($curl);
	//var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
	curl_close($curl);
	return $responseText;
}

/**
 * [yzg_pwd_encode 对用户的密码进行加密]
 * @param  [string] $pwd   [用户传过来md5加密后的密码]
 * @param  [string] $token [我们生成并分配给用户的唯一的验证字段]
 * @return [string]        [加密后的密文]
 */
function yzg_pwd_encode($pwd, $token) {
	$sign       = chr(ord('h') + strlen($token) - 2);
	$stored_pwd = $sign . sha1($token . $pwd) . $token;
	return $stored_pwd;
}

/**
 * [yzg_create_token 生成3-8位的随机token]
 * @return [string] [生成的token]
 */
function yzg_create_token() {
	$len          = mt_rand(3, 8);
	$encrpt_table = '0123456789abcdefghijklmnopqrstuvwxyz';
	$token        = substr(str_shuffle($encrpt_table), -$len);
	return $token;
}

/**
 * [yzg_get_token 从数据库保存的密文中获取token]
 * @param  [string] $stored_pwd [数据库内的密文]
 * @return [string]             [token]
 */
function yzg_get_token($stored_pwd) {
	$len   = ord(substr($stored_pwd, 0, 1)) + 2 - ord('h');
	$token = substr($stored_pwd, -$len);
	return $token;
}
/**
 * [yzg_pwd_create  将一般密文以yzg加密的]
 * @param  [string] $pwd [加密前的字符串]
 * @return [string]      [加密后的密文]
 */
function yzg_pwd_create($pwd) {
	$token          = yzg_create_token();
	return $yzg_pwd = yzg_pwd_encode($pwd, $token);
}
/**
 * [yzg_pwd_compare 将输入的密码与数据库内得到的密文进行比对]
 * @param  [string] $ori_pwd [数据库内的密码]
 * @param  [string] $chk_pwd [输入的密码]
 * @return [boolen]          [相同为true，不同为false]
 */
function yzg_pwd_compare($ori_pwd, $chk_pwd) {
	$token   = yzg_get_token($ori_pwd);
	$cpi_pwd = yzg_pwd_encode($chk_pwd, $token);
	return ($ori_pwd == $cpi_pwd);
}

function remove_xss($val) {
	$val    = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
	$search = 'abcdefghijklmnopqrstuvwxyz';
	$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$search .= '1234567890!@#$%^&*()';
	$search .= '~`";:?+/={}[]-_|\'\\';
	for ($i = 0; $i < strlen($search); $i++) {
		$val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
		$val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
	}
	$ra1   = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
	$ra2   = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	$ra    = array_merge($ra1, $ra2);
	$found = true; // keep replacing as long as the previous round replaced something
	while ($found == true) {
		$val_before = $val;
		for ($i = 0; $i < sizeof($ra); $i++) {
			$pattern = '/';
			for ($j = 0; $j < strlen($ra[$i]); $j++) {
				if ($j > 0) {
					$pattern .= '(';
					$pattern .= '(&#[xX]0{0,8}([9ab]);)';
					$pattern .= '|';
					$pattern .= '|(�{0,8}([9|10|13]);)';
					$pattern .= ')*';
				}
				$pattern .= $ra[$i][$j];
			}
			$pattern .= '/i';
			$replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
			$val         = preg_replace($pattern, $replacement, $val); // filter out the hex tags
			if ($val_before == $val) {
				$found = false;
			}
		}
	}
	return $val;
}

/**
 * 使用特定function对数组中所有元素做处理
 * @param string &$array 要处理的字符串
 * @param string function 要执行的函数
 * @return boolean apply_to_keys_also 是否也应用到key上
 * @access public
 *
 */
function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
	static $recursive_counter = 0;
	if (++$recursive_counter > 1000) {
		die('possible deep recursion attack');
	}
	foreach ($array as $key => $value) {
		if (is_array($value)) {
			arrayRecursive($array[$key], $function, $apply_to_keys_also);
		} else {
			$array[$key] = $function($value);
		}

		if ($apply_to_keys_also && is_string($key)) {
			$new_key = $function($key);
			if ($new_key != $key) {
				$array[$new_key] = $array[$key];
				unset($array[$key]);
			}
		}
	}
	$recursive_counter--;
}

/**
 * 将数组转换为JSON字符串（兼容中文）
 *
 * @param array $array
 *        	要转换的数组
 * @return string 转换得到的json字符串
 * @access public
 *
 */
function yzg_json_encode($array) {
	if (empty($array)) {
		return null;
	}

	arrayRecursive($array, 'urlencode', true);
	$json = json_encode($array);
	return urldecode($json);
}

function uniq_id() {
	$uid = uniqid();
	$uid = str_replace(array('a', 'b', 'c', 'd', 'e', 'f'), array('1', '2', '3', '4', '5', '6'), $uid);
	return $uid . str_pad(mt_rand(0, 100000), 5, '0');
}

function new_doc_id($prefix_name) {
	$id_prefix = C('ID_PREFIX');
	if (empty($id_prefix[$prefix_name])) {
		return null;
	}

	$prefix = $id_prefix[$prefix_name];

	return $prefix . uniq_id();
}

function is_ios_client() {
//暂时还没有自己做ios的ua
	if (empty($_SERVER['HTTP_USER_AGENT'])) {
		return false;
	}

	$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
	if (strpos($ua, "ios") > 0 || strpos($ua, "iphone") > 0 || strpos($ua, "ipad") > 0 || strpos($ua, "ipod") > 0) {
		return true;
	}
	return false;
}

function is_android_client() {
//ycg_android
	if (empty($_SERVER['HTTP_USER_AGENT'])) {
		return false;
	}

	$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
	if (strpos($ua, "ycg_android") > 0) {
		return true;
	}
	return false;
}

function file_upload($File, $FolderPath) {
	$ProjectPath = dirname(dirname(dirname(dirname(__FILE__))));
	$TruePath    = $ProjectPath . '/' . $FolderPath;
	if (!file_exists($TruePath)) {
		mkdir($TruePath);
	}
	$type = strstr($File['name'], '.'); //限制上传格式
	$FileName = md5(uniqid() . time()) . $type;
	$FilePath = $TruePath . '/' . $FileName;
	if (!move_uploaded_file($File['tmp_name'], $FilePath)) {
		return false;
	} else {
		return $FolderPath . $FileName;
	}
}

// 只过滤null 不过滤0
function yzg_array_filter($arr){
	if(empty($arr)) return null;
	$newArr = array();
	foreach($arr as $k=>$v){
		if($v != null){
			$newArr[$k] = $v;
		}
	}
	return $newArr;
}

//判断是否是微信浏览器
function isWXBrowser() {
	if(!empty($_SERVER['HTTP_USER_AGENT'])){
		if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "micromessenger") > 0) {
			return true;
		}
	}
	return false;
}

function get_unit_name($unit_id){
	$unit_name = C('GOODS_UNIT_NAME.'.$unit_id);
	if(empty($unit_name))return null;
	else return $unit_name;
}

/* 二维数组按指定的键值排序 
* $array 数组
* $key排序键值
* $type排序方式
*/
function array_sort($arr, $keys, $type = 'desc') {
    $keysvalue = $new_array = array();
    foreach ($arr as $k => $v) {
        $keysvalue[$k] = $v[$keys];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k => $v) {
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}

?>